﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Security;
using GUI.OpenID;
using BO.Infrastructure.Utils;

namespace GUI.Pages.VietID
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    if (!String.IsNullOrEmpty(Request.QueryString["oauth_token"]))
                    {
                        var timeStamp = "";
                        var nonce = "";
                        string resultAccessToken = connectMing_Step3(out timeStamp, out nonce);
                        connectMing_Step4(resultAccessToken, timeStamp, nonce);
                    }
                    else
                    {
                        var returnOauthToken = "";
                        var timeStamp = "";
                        var nonce = "";
                        returnOauthToken = connectMing_Step1(out timeStamp, out nonce);
                        connectMing_Step2(returnOauthToken, timeStamp, nonce);
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("<script>parent.MingReload();</script>");
                }
            }

        }

        protected void formsAuthenticationTicket()
        {
            var ident = User.Identity as FormsIdentity;
            if (ident != null)
            {
                Response.Write("<script>parent.MingReload();</script>");
            }
        }

        protected string connectMing_Step1(out string timeStamp, out string nonce)
        {
            string normalizedUrl;
            string normalizedRequestParameters;
            //string url_domain = Request.ServerVariables("SERVER_NAME");
            /*Step1 RequestUrl*/
            OAuthBase myOAuth = new OAuthBase();
            timeStamp = myOAuth.GenerateTimeStamp();
            nonce = myOAuth.GenerateNonce();
            Uri requestUrl = new Uri(Util.GetAppSettingValue("bigMingRequestUrl"));
            string currentPageUrl = "";
            if (Request.ServerVariables["HTTPS"] == "")
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToLower().Substring(0, 4) + "://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"].ToString() + Request.ServerVariables["SCRIPT_NAME"];
            }
            else
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToLower().Substring(0, 5).Replace("/", "") + "://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + Request.ServerVariables["SCRIPT_NAME"];
            }
            string signature = myOAuth.MingSignature(requestUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"),
                currentPageUrl, "GET", timeStamp, nonce, "", "", "", OAuthBase.SignatureTypes.HMACSHA1, out normalizedUrl,
                                                        out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
            string return_oauth_token = Util.getData(strGenURL);
            return return_oauth_token;
        }

        protected void connectMing_Step2(string return_oauth_token, string timeStamp, string nonce)
        {
            string normalizedUrl;
            string normalizedRequestParameters;
            string currentPageUrl = "";
            if (Request.ServerVariables["HTTPS"] == "")
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToLower().Substring(0, 4) + "://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + Request.ServerVariables["SCRIPT_NAME"];
            }
            else
            {
                currentPageUrl = Request.ServerVariables["SERVER_PROTOCOL"].ToLower().Substring(0, 5) + "://" + Request.ServerVariables["SERVER_NAME"] + ":" + Request.ServerVariables["SERVER_PORT"] + Request.ServerVariables["SCRIPT_NAME"];
            }
            OAuthBase myOAuth = new OAuthBase();
            Uri authenticateUrl = new Uri(Util.GetAppSettingValue("bigMingAuthenticateUrl"));
            string token = "";
            string tokenSercret = "";
            string result1 = return_oauth_token;
            string[] arrResult1 = result1.Split('&');
            if (arrResult1.Length > 1)
            {
                token = arrResult1[0].Substring(arrResult1[0].IndexOf('=') + 1);
                tokenSercret = arrResult1[1].Substring(arrResult1[1].IndexOf('=') + 1);
            }
            Session["tokenSercret"] = tokenSercret;
            string signature = myOAuth.MingSignature(authenticateUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), currentPageUrl, "GET", timeStamp, nonce, "",
                HttpUtility.UrlDecode(token), HttpUtility.UrlDecode(tokenSercret), GUI.OpenID.OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);
            string strGenURL1 = normalizedUrl + "?" + normalizedRequestParameters + "&no_connect=1&oauth_signature=" + signature;
            string strGenURL2 = normalizedUrl + "?oauth_token=" + token;

            Response.Redirect(strGenURL2);
            string result = string.Empty;
            WebRequest wrq = WebRequest.Create(strGenURL2);
            WebResponse wrs = wrq.GetResponse();

            StreamReader strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
            result = strdr.ReadToEnd();
            strdr.Close();
            wrs.Close();
            Response.Write(result);
        }

        protected string connectMing_Step3(out string timeStamp, out string nonce)
        {
            //Response.Write("step3");
            string normalizedUrl;
            string normalizedRequestParameters;

            OAuthBase myOAuth = new OAuthBase();
            timeStamp = myOAuth.GenerateTimeStamp();
            nonce = myOAuth.GenerateNonce();
            Uri uriAccessUrl = new Uri(Util.GetAppSettingValue("bigMingAccessUrl"));
            string oauth_token = Request.QueryString["oauth_token"];
            if (oauth_token == null) oauth_token = Request.Form["oauth_token"];
            string oauth_verifier = Request.QueryString["oauth_verifier"];
            if (oauth_verifier == null) oauth_verifier = Request.Form["oauth_verifier"];
            if (oauth_verifier.Contains("?")) oauth_verifier = oauth_verifier.Substring(0, oauth_verifier.IndexOf('?'));

            string signature = myOAuth.MingSignature(uriAccessUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), "", "GET", timeStamp, nonce, oauth_verifier,
                HttpUtility.UrlDecode(oauth_token), HttpUtility.UrlDecode(Session["tokenSercret"].ToString()), OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);

            string resultAccessToken = Util.getData(strGenURL);
            //Response.Write("end step3");
            return resultAccessToken;
        }

        protected void connectMing_Step4(string resultAccessToken, string timeStamp, string nonce)
        {
            //Response.Write("step4");
            string token = "";
            string tokenSercret = "";
            string normalizedUrl;
            string normalizedRequestParameters;

            OAuthBase myOAuth = new OAuthBase();
            Uri apiUrl = new Uri(Util.GetAppSettingValue("bigMingAPIUrl"));
            List<OAuthBase.QueryParameter> lstToken = Util.GetQueryParameters(resultAccessToken);
            string[] arrResult1 = resultAccessToken.Split('&');
            if (arrResult1.Length > 1)
            {
                token = arrResult1[0].Substring(arrResult1[0].IndexOf('=') + 1);
                tokenSercret = arrResult1[1].Substring(arrResult1[1].IndexOf('=') + 1);
            }
            string signature = myOAuth.MingSignature(apiUrl, Util.GetAppSettingValue("mingConsumerKey"), Util.GetAppSettingValue("mingConsumerSecret"), "", "GET", timeStamp, nonce, "",
                HttpUtility.HtmlDecode(token), HttpUtility.HtmlDecode(tokenSercret), OAuthBase.SignatureTypes.HMACSHA1,
                out normalizedUrl, out normalizedRequestParameters);

            string strGenURL = normalizedUrl + "?" + normalizedRequestParameters + "&oauth_signature=" + myOAuth.UrlEncode(signature);
            //Response.Write("step41");
            getData(strGenURL);
        }

        protected void getData(string url)
        {
            try
            {
                //Response.Write("step42");
                string result = string.Empty;

                var wrq = WebRequest.Create(url);
                var wrs = wrq.GetResponse();

                var strdr = new StreamReader(wrs.GetResponseStream(), Encoding.UTF8);
                result = strdr.ReadToEnd();
                strdr.Close();
                wrs.Close();

                var mingUser = Ming.ConvertMingJson(result);
                if (!string.IsNullOrEmpty(mingUser.user.username))
                {
                    //Response.Write("end step4");

                    var userDataString = mingUser.user.id + "|" + mingUser.user.username + "|" + mingUser.user.email + "|" + mingUser.user.full_name + "|" + mingUser.user.avatar + "|" + mingUser.user.gender;

                    HttpCookie authCookie = FormsAuthentication.GetAuthCookie(mingUser.user.username, true);
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
                    FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);
                    authCookie.Value = FormsAuthentication.Encrypt(newTicket);
                    authCookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(authCookie);
                    Response.Write("<script>parent.MingReload();</script>");
                }
            }
            catch (Exception ex)
            {
                Response.Write("<script>parent.MingReload();</script>");
            }
        }
    }

    public class Ming
    {
        public static ReturnMingUser ConvertMingJson(string result)
        {
            return PresentationUtils.JsonToObject<ReturnMingUser>(result);

        }
    }

    public class ReturnMingUser
    {
        public ReturnUser user;
    }

    public class ReturnUser
    {
        public int id;
        public string username;
        public string email;
        public string avatar;
        public string birthday;
        public string full_name;
        public int gender;
        public int level;
        public string last_login;
        public string join_time;
        public string modified_time;
        public string convert_from;
        public string old_last_login;
        public int status;
    }
}